# -*- encoding: utf-8 -*-
'''
@File    :   condition_query.py    
@Contact :   ypy02784@163.com
@License :   (C)Copyright 2019-2020, ypy

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2020/3/7 17:09   ypy      1.0         None
'''
from . import models
from django.db.models import Max


def query_stock_with_conditons(trade_date, condition_list):
    """
    根据传入条件列表查询数据
    :param condition_list: 条件列表,每个项为字典数据包括查询条件名称，操作大于或等于，条件值 例如 pct_chg  >=   5，代表查询涨幅大于等于5%的股票,需要和analysis.js文件项匹配
    :return: 返回股票代码列表和股票名称列表
    """
    if len(condition_list) == 0:
        return None, None  # 无条件列表，则返回空
    if (trade_date == ''):
        starttime = models.daily.objects.all().aggregate(Max('trade_date'))
        trade_date = starttime['trade_date__max']

    daily_set = models.daily.objects.filter(trade_date=trade_date)
    code_list = []  # 初始集，符合交易日期的所有ts_code,用来做交集用的
    for daily in daily_set:
        code_list.append(daily.ts_code)

    # 由于condition_list是双重json格式，所以第一层循环，先把第一层所有的key值读出来，对应的键值对相应为
    """
        //具体事例如下所示：例如市盈率，资金总流入字段等字段的值，后台按值1<field<=值2的方式查询，或者如连续涨跌，值1为涨或者跌，即up或者down，值2为具体天数。
        {
        "流动市值":{query_field "circ_mv", field_value1 = '10', field_value2 = '20'},表示市值大于 10万小于20万，
        "市盈率": "pe_ttm",
        "换手率": "turnover_rate_f",
        "当日涨幅": "pct_chg",
        "总流入资金": "net_mf_amount",
        "主力净流入": "main_in",
        "主力换手占比": "main_turnover_rate",
        "连续涨跌": "continuous_up_or_down",
        "连续资金流入": {query_field "continuous_in_or_out", field_value1 = '3', field_value2 = 'in'}表示资金连续3天流入
        "连续换手率": "continuous_turnover_rate", field_value1 ='3',field_value2 = '5' 表示换手率连续3天大于5%
        }
    """
    # 循环开始后通过求集合之间的交集方式求出符合多条件的股票
    for key in condition_list:
        dic_condition = condition_list[key]

        # 涨幅百分比
        if dic_condition['query_field'] == 'pct_chg':
            minValue = dic_condition['field_value1']
            maxValue = dic_condition['field_value2']

            eligible_list = models.daily.objects.filter(pct_chg__lte=maxValue, pct_chg__gte=minValue,
                                                        trade_date=trade_date)

            compare_code_list = []
            for eligible in eligible_list:
                compare_code_list.append(eligible.ts_code)
            code_list = list(set(code_list) & set(compare_code_list))
        # 换手率（自由流通）
        if dic_condition['query_field'] == 'turnover_rate_f':
            minValue = dic_condition['field_value1']
            maxValue = dic_condition['field_value2']

            eligible_list = models.daily_basic.objects.filter(turnover_rate_f__lte=maxValue,
                                                              turnover_rate_f__gte=minValue, trade_date=trade_date)

            compare_code_list = []
            for eligible in eligible_list:
                compare_code_list.append(eligible.ts_code)
            code_list = list(set(code_list) & set(compare_code_list))
        # 流通市值
        if dic_condition['query_field'] == 'circ_mv':
            minValue = dic_condition['field_value1']
            maxValue = dic_condition['field_value2']

            eligible_list = models.daily_basic.objects.filter(circ_mv__lte=maxValue, circ_mv__gte=minValue,
                                                              trade_date=trade_date)

            compare_code_list = []
            for eligible in eligible_list:
                compare_code_list.append(eligible.ts_code)
            code_list = list(set(code_list) & set(compare_code_list))
        # 主力净流入
        if dic_condition['query_field'] == 'main_in':
            minValue = dic_condition['field_value1']
            maxValue = dic_condition['field_value2']

            eligible_list = models.pre_analysis_main_moneyflow.objects.filter(main_in__lte=maxValue,
                                                                              main_in__gte=minValue,
                                                                              trade_date=trade_date)

            compare_code_list = []
            for eligible in eligible_list:
                compare_code_list.append(eligible.ts_code)
            code_list = list(set(code_list) & set(compare_code_list))
        # 主力占交易还手流通比
        if dic_condition['query_field'] == 'main_turnover_rate':
            minValue = dic_condition['field_value1']
            maxValue = dic_condition['field_value2']
            eligible_list = models.pre_analysis_main_moneyflow.objects.filter(main_turnover_rate__lte=maxValue,
                                                                              main_turnover_rate__gte=minValue,
                                                                              trade_date=trade_date)

            compare_code_list = []
            for eligible in eligible_list:
                compare_code_list.append(eligible.ts_code)
            code_list = list(set(code_list) & set(compare_code_list))
        # 市净率
        if dic_condition['query_field'] == 'pe_ttm':
            minValue = dic_condition['field_value1']
            maxValue = dic_condition['field_value2']

            eligible_list = models.daily_basic.objects.filter(pe_ttm__lte=maxValue, pe_ttm__gte=minValue,
                                                              trade_date=trade_date)

            compare_code_list = []
            for eligible in eligible_list:
                compare_code_list.append(eligible.ts_code)
            code_list = list(set(code_list) & set(compare_code_list))
        # 总流入资金
        if dic_condition['query_field'] == 'net_mf_amount':
            minValue = dic_condition['field_value1']
            maxValue = int(dic_condition['field_value2'])

            eligible_list = models.moneyflow.objects.filter(net_mf_amount__lte=maxValue, net_mf_amount__gte=minValue,
                                                            trade_date=trade_date)

            compare_code_list = []
            for eligible in eligible_list:
                compare_code_list.append(eligible.ts_code)
            code_list = list(set(code_list) & set(compare_code_list))

        # 连续涨幅
        if dic_condition['query_field'] == 'continuous_up_or_down':
            continuouNnum = dic_condition['field_value1']  # 连续天数，正整数
            operator = dic_condition['field_value2']  # 涨或者跌，取值为up或者down

            # 获取具体时间日期
            days = models.daily.objects.all().values('trade_date').distinct().order_by('-trade_date')[0:int(continuouNnum)]

            if operator == 'up':
                firstday = models.daily.objects.filter(trade_date=trade_date, pct_chg__gte=0)  # 即trade_date当天涨幅大于0的数据
            else:
                firstday = models.daily.objects.filter(trade_date=trade_date, pct_chg__lte=0)  # 即trade_date当天涨幅小于0的数据

            firstday_code_list = []
            for eligible in firstday:
                firstday_code_list.append(eligible.ts_code)

            for i in range(1, int(continuouNnum) ):
                day = days[i]['trade_date']
                if operator == 'up':
                    otherday = models.daily.objects.filter(trade_date=day,
                                                           pct_chg__gte=0)  # 即trade_date当天涨幅大于0的数据
                else:
                    otherday = models.daily.objects.filter(trade_date=day,
                                                           pct_chg__lte=0)  # 即trade_date当天涨幅小于0的数据
                otherday_code_list = []
                for eligible in otherday:
                    otherday_code_list.append(eligible.ts_code)
                firstday_code_list = list(set(firstday_code_list) & set(otherday_code_list))
            code_list = list(set(code_list) & set(firstday_code_list))

        # 连续资金流入
        if dic_condition['query_field'] == 'continuous_in_or_out':
            continuouNnum = dic_condition['field_value1']  # 连续天数，正整数
            operator = dic_condition['field_value2']  # 涨或者跌，取值为up或者down

            # 获取具体时间日期
            days = models.moneyflow.objects.all().values('trade_date').distinct().order_by('-trade_date')[0:int(continuouNnum)]

            if operator == 'in':
                firstday = models.moneyflow.objects.filter(trade_date=trade_date, net_mf_amount__gte=0)  # 即trade_date当天涨幅大于0的数据
            else:
                firstday = models.moneyflow.objects.filter(trade_date=trade_date, net_mf_amount__lte=0)  # 即trade_date当天涨幅小于0的数据

            firstday_code_list = []
            for eligible in firstday:
                firstday_code_list.append(eligible.ts_code)

            for i in range(1, int(continuouNnum)):
                day = days[i]['trade_date']
                if operator == 'in':
                    otherday = models.moneyflow.objects.filter(trade_date=day,
                                                           net_mf_amount__gte=0)  # 即trade_date当天涨幅大于0的数据
                else:
                    otherday = models.moneyflow.objects.filter(trade_date=day,
                                                           net_mf_amount__lte=0)  # 即trade_date当天涨幅小于0的数据
                otherday_code_list = []
                for eligible in otherday:
                    otherday_code_list.append(eligible.ts_code)
                firstday_code_list = list(set(firstday_code_list) & set(otherday_code_list))
            code_list = list(set(code_list) & set(firstday_code_list))

        #连续换手率
        if dic_condition['query_field'] == 'continuous_turnover_rate':
            continuouNnum = dic_condition['field_value1']  # 连续天数，正整数
            operator = dic_condition['field_value2']  # 每天换手率大于的值

            # 获取具体时间日期
            days = models.moneyflow.objects.all().values('trade_date').distinct().order_by('-trade_date')[
                   0:int(continuouNnum)]

            firstday = models.daily_basic.objects.filter(trade_date=trade_date,
                                                           turnover_rate_f__gte=operator)  # 即trade_date当天涨幅大于0的数据


            firstday_code_list = []
            for eligible in firstday:
                firstday_code_list.append(eligible.ts_code)

            for i in range(1, int(continuouNnum)):
                day = days[i]['trade_date']

                otherday = models.daily_basic.objects.filter(trade_date=day,
                                                           turnover_rate_f__gte=operator)  # 即trade_date当天涨幅大于0的数据

                otherday_code_list = []
                for eligible in otherday:
                    otherday_code_list.append(eligible.ts_code)
                firstday_code_list = list(set(firstday_code_list) & set(otherday_code_list))
            code_list = list(set(code_list) & set(firstday_code_list))

    name_list = select_name_by_ts_code(code_list)
    return code_list, name_list


def select_name_by_ts_code(ts_code_list):
    """
    根据输入的ts_code列表，查询列表中股票名称
    :param ts_code_list: 股票tscode列表
    :return: 返回相应股票的最新交易日期的数据,如传入参数为空，则返回None
    """
    if (len(ts_code_list) == 0): return None
    stock_daily_list = []
    name_daily_list = []
    for tscode in ts_code_list:
        try:
            name = models.stock_basic.objects.filter(ts_code=tscode)[0]
        except:
            print(tscode)
            name_daily_list.append('error')
            continue
        name_daily_list.append(name.name)
    return name_daily_list
